package com.cockybook.poemspider.job;

import com.cockybook.poemspider.beans.Poem;
import com.cockybook.poemspider.dao.PoemsRepository;
import com.cockybook.utils.Const;
import com.cockybook.utils.JsoupUtil;
import com.cockybook.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.print.Doc;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 抓取诗歌
 */
//@Component
//@Order(1)
public class PoemSpiderWithAuthorID implements CommandLineRunner {

    private final Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    PoemsRepository poemsRepository;

    Map<String ,String> dynastys =new HashMap<String, String>();

    int MAXCOUNT=1;

    public PoemSpiderWithAuthorID(){
        this.dynastys.put("xianqinshiren","先秦");
        this.dynastys.put("hanchaoshiren","汉朝");
        this.dynastys.put("weijinshiren","魏晋");
        this.dynastys.put("nanbeichaoshiren","南北朝");
        this.dynastys.put("suichaoshiren","隋");
        this.dynastys.put("tangdaishiren","唐");
        this.dynastys.put("songdaishiren","宋");
        this.dynastys.put("jinchaoshiren","金");
        this.dynastys.put("liaochaoshiren","辽");
        this.dynastys.put("yuanchaoshiren","元");
        this.dynastys.put("mingchaoshiren","明");
        this.dynastys.put("qingchaoshiren","清");
        this.dynastys.put("xiandangdaishiren","近当代");
    }

    @Override
    public void run(String... args) throws Exception {
        for (int authID = 1; authID < MAXCOUNT; authID++) {
            logger.info("start download index : "+ authID);
            parseDynasty(String.format(Const.srcURL+Const.srcURLAuthorPREFINX,authID),authID, true);
        }

    }

    /**
     * parse page one
     * @param url
     * @param isGodownPage  是否下钻
     */
    public void parseDynasty(String url, int authID ,boolean isGodownPage) throws Exception {
        Document document =null;
        try {
            document = JsoupUtil.urlGet(url);
        }catch (Exception e){
            logger.info("faild id:"+ authID , e);
            return;
        }
        String  num=document.getElementById("zzform").getElementsByTag("b").text();

        double total=0;

        if(StringUtils.isNumeric(num)){
            total = Integer.parseInt(num)/40.0;
        }

        parsePagePoem(document);

        //total
        logger.info(String.format("total: %s,page: %s",num,total));

        //page
        for (int pageId = 2; pageId < total+1; pageId++) {
            try {
                document = JsoupUtil.urlGet(String.format(Const.srcURL+Const.srcURLAuthorPREFINX_PAGE,authID,pageId));
            }catch (Exception e){
                logger.info(String.format("authorID: %s, PoemID:%s ",authID,pageId), e);
                continue;
            }
            parsePagePoem(document);
        }

    }

    /**
     * parse page
     * @param document
     * @throws Exception
     */
    private void parsePagePoem(Document document) throws Exception {
        Elements elementsByAttributeValueContaining = document.getElementById("middlediv").getElementsByAttributeValueContaining("href", "/chaxun/list");
        Iterator<Element> iterator = elementsByAttributeValueContaining.iterator();
        while (iterator.hasNext()){
            String url  = Const.srcURL+iterator.next().attr("href");
            Poem poem = parsePoem(url, StringUtil.getAuthIntID(url));
            if(poem!=null){
                addPoem(poem);
            }
        }
    }

    /**
     * parse Poem
     * @param url
     * @param peomID
     * @return
     * @throws Exception
     */
    private Poem parsePoem(String url ,int peomID) throws Exception {
        Document document =null;
        try {
            document = JsoupUtil.urlGet(url);
        }catch (Exception e){
            logger.info("faild id:"+ peomID , e);
            return null;
        }
        if(document!=null){
            logger.info("Title: "+document.title() +" ： "+peomID);

            Poem poem = new Poem();
            poem.setId(peomID);

            //author name
            Element nameEle = document.getElementById("middlediv").getElementsByClass("zhuti").get(0).getElementsByTag("h2").get(0);
            poem.setTitle(StringUtil.getPoemName(nameEle.text()));

            Elements jjzz = document.getElementsByClass("jjzz");

            if(jjzz.size()>0) {
                //dynastyURL
                String dynastyURL =jjzz.get(0).getElementsByAttributeValueContaining("href", "/category/").attr("href");
                poem.setDynasty(StringUtil.getDynasty(dynastyURL));
                poem.setDynastyReal(this.dynastys.get(poem.getDynasty()));

                Elements zuozhe = jjzz.get(0).getElementsByAttributeValueContaining("href", "/chaxun/zuozhe/");
                //poems total
                String author = zuozhe.text();
                poem.setPoetName(author);

                poem.setPoetId(StringUtil.getAuthID(zuozhe.attr("href")));

//                String title = jjzz.get(0).getElementsByTag("h2").get(0).text();
//
//                poem.setTitle(StringUtil.getPoemName(title));

            }

            //introduction
            Elements zuozhe = document.getElementsByClass("zuozhe");


            //header img
            String content = document.getElementById("shicineirong").html();
            poem.setContent(content);
            if(content.startsWith("诗句：")){
                poem.setIsShiju(1);
            }

            String intro= document.getElementsByClass("shangxi").html();
            poem.setIntroduction(intro);

            //TODO labels  解析



            return poem;
        }
        return null;
    }

    /**
     * 添加一个诗人
     * @param poet
     * @throws Exception
     */
    private void addPoem(Poem poet) throws Exception {

        if (! poemsRepository.exists(poet.getId())){
            poemsRepository.saveAndFlush(poet);
        }

        logger.info(poet.toString());

    }

}
